<template>
  <div id="goods-detail">
    <top-header title="商品详情" :isRoute="isRoute" />
    <div class="goods-images">
      <self-swiper :data="swiperData" />
    </div>
    <div class="info">
      <h3 class="title">{{goodsDetail.title}}</h3>
      <mt-button type="primary" @click="addShopcart">加入购物车</mt-button>
      <button class="jian-btn" @click="jianQuantity">-</button>
      <input type="number" v-model="quantity" class="quantity" disabled />
      <button class="add-btn" @click="addQuantity">+</button>
      <p>商品编号：{{goodsDetail.goods_no}}</p>
      <del class="market-price">原价：{{goodsDetail.market_price}}</del>
      <p class="sell-price">现价：{{goodsDetail.sell_price}}</p>
      <p>上架时间：{{goodsDetail.add_time | formatDate}}</p>
      <p>库存：{{goodsDetail.stock_quantity}}</p>
      <mt-button type="primary" style="width:10rem;" @click="goComment">点击评论</mt-button>
    </div>
    <keep-alive>
      <transition name="ball" mode="in-out" @after-enter="killFlyBall">
        <div class="fly-ball" v-if="isBallShow"></div>
      </transition>
    </keep-alive>
  </div>
</template>
<script>
import "./index.less";
import { map, each, find } from "lodash";
import { shopcartData, userData, middleVue } from "../../services";
export default {
  data() {
    return {
      isRoute: true,
      goodsDetail: {},
      swiperData: {
        className: "home-swipe",
        swipeList: []
      },
      quantity: 0,
      isBallShow: false,
      onLineShopcartList: []
    };
  },
  methods: {
    goComment() {
      if (userData.getUserData()) {
        this.$router.push({
          name: "comment",
          query: {
            goodsId: this.goodsDetail.id
          }
        });
      } else {
        middleVue.$emit("openLoginRegist", true);
      }
    },
    jianQuantity() {
      if (this.quantity <= 0) {
        return;
      }
      this.quantity--;
    },
    addQuantity() {
      if (this.quantity >= this.goodsDetail.stock_quantity) {
        return;
      }
      this.quantity++;
    },
    async addShopcart() {
      // 至少选择一个商品添加购物车的判断
      if (this.quantity <= 0) {
        this.$toast({
          message: `至少添加一件商品到购物车中`,
          position: "bottom"
        });
        return;
      }
      // 判断用户是否登录，如果用户登录则调用接口来添加在线购物车，如果用户未登录则添加离线购物车
      if (userData.getUserData()) {
        // 先查询当前用户的购物车数据，判断当前操作商品的数量是否超出库存
        const shopcartListResponse = await this.$axios.get("getshopcarts", {
          params: {
            account: userData.getUserData()
          }
        });
        this.onLineShopcartList = shopcartListResponse.data.message;
        const currentGoods = find(this.onLineShopcartList, item => {
          return item.goodsId === this.goodsDetail.id;
        });
        // 如果小于库存数量，则加车，否则弹框提示
        if (currentGoods) {
          if (
            currentGoods.quantity + this.quantity <
            currentGoods.stock_quantity
          ) {
            const addSuccessResponse = await this.$axios.post("add_shopcart", {
              user_name: userData.getUserData(),
              goodsId: this.goodsDetail.id,
              quantity: this.quantity
            });
            console.log(addSuccessResponse.data.msg);
          } else {
            this.$toast({
              message: "库存不足！请重新操作！",
              position: "bottom"
            });
          }
        } else {
          const addSuccessResponse = await this.$axios.post("add_shopcart", {
            user_name: userData.getUserData(),
            goodsId: this.goodsDetail.id,
            quantity: this.quantity
          });
          console.log(addSuccessResponse.data.msg);
        }
      } else {
        const msg = shopcartData.setShopcartData({
          goodsId: this.goodsDetail.id,
          quantity: this.quantity,
          stockQuantity: this.goodsDetail.stock_quantity,
          title: this.goodsDetail.title,
          sell_price: this.goodsDetail.sell_price,
          img_url: this.swiperData.swipeList[0].src
        });
        if (msg) {
          this.$toast({
            message: msg,
            position: "bottom"
          });
          return;
        }
        // console.log(shopcartData.getShopcartData());
      }
      this.isBallShow = true;
    },
    async killFlyBall() {
      this.isBallShow = false;
      let resultQuantity = 0;
      if (userData.getUserData()) {
        const response = await this.$axios.get("getshopcarts", {
          params: {
            account: userData.getUserData()
          }
        });
        console.log("response=", response);
        each(response.data.message, item => {
          resultQuantity += item.quantity;
        });
      } else {
        const shopcartList = shopcartData.getShopcartData();
        const shopcartQuantityList = [];
        each(shopcartList, item => {
          shopcartQuantityList.push(item.quantity);
        });
        resultQuantity = shopcartQuantityList.reduce((prev, next) => {
          return prev + next;
        });
      }
      // let resultQuantity = 0;
      // each(shopcartList, item => {
      //   resultQuantity += item.quantity;
      // });
      middleVue.$emit("getTotalQuantity", resultQuantity);
    }
  },
  created() {
    this.$axios
      .all([
        this.$axios.get("getgoodsthumimages/" + this.$route.params.id),
        this.$axios.get("goods/getinfo/" + this.$route.params.id)
      ])
      .then(
        this.$axios.spread((resImages, resInfo) => {
          this.swiperData.swipeList = resImages.data.message;
          map(this.swiperData.swipeList, item => {
            item.url = "";
            return item;
          });
          this.goodsDetail = resInfo.data.message;
        })
      )
      .catch(err => console.log(err));
  }
};
</script>
